package com.ourcraft.informationcollectionsystem.service.company.companyDataQuery;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.*;
import com.ourcraft.informationcollectionsystem.mapper.CompanyMapper;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormHistoryMapper;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * CompanyDataQueryServiceImpl provide dataReportForm-query-related services interface implementation.
 *
 * @author Liu Yiming
 * @since 2023-11-04
 */
@Service
public class CompanyDataQueryServiceImpl implements CompanyDataQueryService{

    @Autowired
    DataReportFormMapper dataReportFormMapper;

    @Autowired
    CompanyMapper companyMapper;

    /**
     * Determine whether the status is submitted status.
     *
     * @param status The status to be determined.
     * @return whether the status is submitted status.
     */
    private boolean formInSubmittedStatus(int status) {
        return status == 2 || status == 4 || status == 6 || status == 7;
    }

    /**
     * Get the status's chinese name.
     *
     * @param status The status.
     * @return chinese name of the status.
     */
    private String getStatusName(int status) {
        if (status == 2) {
            return "待市审批";
        } else if (status == 4){
            return "待省审批";
        } else if (status == 6){
            return "省审核通过";
        } else {
            return "省上报国家";
        }
    }

    /**
     * Retrieves information of list of all forms recording to user ID
     *
     * @param userId The ID of the user.
     * @return information of list of all forms.
     */
    @Override
    public ArrayList<Map<String, Object>> getAllQueryDataInfo(int userId) {
        ArrayList<Map<String, Object>> returnData = new ArrayList<>();
        // 筛选出需要填写的表单
        List<CompanyDataReportForm> companyDataReportForm = dataReportFormMapper.selectCompanyDataReportForm();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 筛选表单
        for (CompanyDataReportForm item : companyDataReportForm) {
            // 筛选条件为：指根据userId获取当前企业的数据报表，并且只获取已经提交的数据报表
            if (item.getUserId() == userId && formInSubmittedStatus(item.getFormExamineStatus())) {
                Map<String, Object> map = new HashMap<>();
                // 添加键值对
                map.put("formID", item.getFormId());
                map.put("formDecreaseType", item.getFormDecreaseType());
                map.put("formStartTotalNum", item.getFormStartTotalNum());
                map.put("formEndTotalNum", item.getFormEndTotalNum());
                Date startDate = item.getFormStartDate();
                long millisecondsToAdd = item.getInvestigationLength() * 24 * 60 * 60 * 1000L; // 将天数转换为毫秒
                Date endDate = new Date(startDate.getTime() + millisecondsToAdd);
                String strStartDate = dateFormat.format(startDate);
                String strEndDate = dateFormat.format(endDate);
                map.put("formStartDate", strStartDate);
                map.put("formEndDate", strEndDate);
                map.put("formIsDecrease", (item.getFormStartTotalNum() == null || item.getFormStartTotalNum() >= item.getFormEndTotalNum()) ? "否" : "是");
                map.put("formFirstReason", item.getFormFirstReason());
                map.put("formExamineStatus", getStatusName(item.getFormExamineStatus()));
                // 格式化最后提交日期
                String date_str = getLastSubmitDate(item.getFormId());
                map.put("historyDate", date_str);
                returnData.add(map);
            }
        }
        return returnData;
    }

    @Autowired
    DataReportFormHistoryMapper dataReportFormHistoryMapper;

    /**
     * Get the last submit date from database recording to formId.
     *
     * @param formId The ID of the form.
     * @return last submit date of the form's record.
     */
    private String getLastSubmitDate(int formId) {
        SimpleDateFormat submitDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 根据form ID筛选出该企业备案信息的所有历史记录
        QueryWrapper<DataReportFormHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_id", formId);
        queryWrapper.eq("history_type", 0);
        queryWrapper.orderByDesc("history_date");
        List<DataReportFormHistory> dataReportFormHistoryList = dataReportFormHistoryMapper.selectList(queryWrapper);
        if (dataReportFormHistoryList.isEmpty()) {
            return "";
        }
        // 找到最后一次提交的历史记录并返回提交日期
        Date returnDate = dataReportFormHistoryList.get(0).getHistoryDate();
        for (DataReportFormHistory history : dataReportFormHistoryList) {
            Date currentDate = history.getHistoryDate();
            if (currentDate.after(returnDate)) {
                returnDate = currentDate;
            }
        }
        return submitDateFormat.format(returnDate);
    }

    /**
     * Get the company's company name from database recording to company ID.
     *
     * @param companyId The ID of the company.
     * @return company name of the company.
     */
    private String getCompanyName(int companyId){
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", companyId);
        Company company = companyMapper.selectOne(queryWrapper);
        return company.getCompanyChineseName();
    }

    /**
     * Retrieves information of a form recording to formId ID
     *
     * @param formId The ID of the form.
     * @return information of the forms.
     */
    @Override
    public Map<String, Object> getQueryFormInfo(int formId) {
        Map<String, Object> returnData = new HashMap<>();
        // 筛选表单
        QueryWrapper<DataReportForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_Id", formId);
        DataReportForm dataReportForm = dataReportFormMapper.selectOne(queryWrapper);
        if (dataReportForm != null) {
            // 添加键值对
            returnData.put("formId", dataReportForm.getFormId());
            returnData.put("companyId", dataReportForm.getCompanyId());
            returnData.put("investigationId", dataReportForm.getInvestigationId());
            returnData.put("formStartTotalNum", dataReportForm.getFormStartTotalNum());
            returnData.put("formEndTotalNum", dataReportForm.getFormEndTotalNum());
            returnData.put("formDecreaseType", dataReportForm.getFormDecreaseType());
            returnData.put("formFirstReason", dataReportForm.getFormFirstReason());
            returnData.put("formSecondReason", dataReportForm.getFormSecondReason());
            returnData.put("formThirdReason", dataReportForm.getFormThirdReason());
            returnData.put("formReasonDescription", dataReportForm.getFormReasonDescription());
            returnData.put("formExamineStatus", dataReportForm.getFormExamineStatus());
            returnData.put("companyChineseName", getCompanyName(dataReportForm.getCompanyId()));
        }
        return returnData;
    }
}
